package com.topone.controller;

import com.topone.Utils.ResultVOUntil;
import com.topone.VO.ResultVO;
import com.topone.config.UploadConfig;
import com.topone.dataObject.Image;
import com.topone.service.ImageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
@CrossOrigin
public class CommonController {

    @Autowired
    private UploadConfig uploadConfig;

    @Autowired
    private ImageService imageService;

    @Autowired
    private Environment env;

    @PostMapping("/saveImage")
    public ResultVO saveConvenientImages(@RequestParam("file") MultipartFile multipartFile,
                                         @RequestParam(value = "description", required = false) String description) {
        Map<String, Object> map = new HashMap<>();
        Image image = new Image();
        //处理上传文件
        // 获取上传文件的路径
        String uploadConvenientImgPath = uploadConfig.getBussinessImgPath();
        // 截取上传文件的文件名
        String uploadConvenientImgName = UUID.randomUUID().toString()
                .replace("-", "");
        ///截取上传文件的后缀
        String originalName = multipartFile.getOriginalFilename();
        String fileType = originalName
                .substring(originalName.indexOf('.') + 1, originalName.length());
        //文件全路径
        String filePath = uploadConvenientImgPath + uploadConvenientImgName + "." + fileType;
        FileOutputStream fos = null;
        FileInputStream fis = null;
        try {
            File file = new File(uploadConvenientImgPath);
            if (!file.exists()) {   //图片路径不存在，创建路径
                file.mkdirs();
            }
                fis = (FileInputStream) multipartFile.getInputStream();
            fos = new FileOutputStream(new File(filePath));
            long size = fis.available();
            if (size > 104865760) {  //上传最大限制10M
                log.error("【图片上传】上传文件过大");
                return ResultVOUntil.error(1, "【图片上传】上传文件过大");
            }
            byte[] data = new byte[fis.available()];
            fis.read(data);
            fos.write(data);
            image.setImgPath(filePath);
            if (StringUtils.isNotEmpty(description)) {
                image.setDescription(description);
            }
            image = imageService.saveImage(image);
            log.info("----wechat.domain--{}",env.getProperty("wechat.domain"));
            if (StringUtils.equals(env.getProperty("wechat.domain"), "bg")) {
                image.setImgUrl("http://b.qingzhao.net.cn/fanZone/file/image/" + image.getId());
            } else {
                image.setImgUrl("http://wx.qingzhao.net.cn/fanZone/file/image/" + image.getId());
            }
            image = imageService.saveImage(image);

        } catch (IOException e) {
            log.error("【图片上传】异常, {}", e.getStackTrace());
            return ResultVOUntil.error(1, "【图片上传】异常");
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                log.error("【图片上传】异常, {}", e.getStackTrace());
                return ResultVOUntil.error(1, "图片上传】异常");
            }
        }
        map.put("image", image);
        return ResultVOUntil.success(map);
    }


}
